import axios from 'axios';
import { showToast } from 'vant';

const baseURL = '/api';
const service = axios.create({
  baseURL,
  timeout: 10000,
});

service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      // config.params = { token };
      config.headers = {
        'x-access-token': token,
      };
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (response.status !== 200) {
      // 请求失败的逻辑
      return Promise.reject(new Error(res.message || 'Error'));
    } else {
      // 请求成功的逻辑
      if (res.code === 200) {
        return res.result;
      } else {
        showToast(res.success);
      }
    }
  },
  (err) => {
    return Promise.reject(err);
  }
);

export default service;
